//
// Created by robin on 4/7/16.
//

#include "ContentValues.h"
#include <sstream>

namespace duomai {

    namespace im {

        ContentValues::ContentValues() {}

        ContentValues::~ContentValues() {}

        void ContentValues::put(string key, int value) {
            Data data;
            data.INT = value;
            values.insert(make_pair(key, Value(SQLITEWRAPPER_INTEGER, data)));
        }

        void ContentValues::put(string key, int64_t value) {
            Data data;
            data.INT = value;
            values.insert(make_pair(key, Value(SQLITEWRAPPER_INTEGER, data)));
        }

        void ContentValues::put(string key, string value) {
            Data data;
            data.TEXT = value.c_str();
            values.insert(make_pair(key, Value(SQLITEWRAPPER_TEXT, data)));
        }

        void ContentValues::put(string key, float value) {
            Data data;
            data.FLOAT = value;
            values.insert(make_pair(key, Value(SQLITEWRAPPER_FLOAT, data)));
        }

        void ContentValues::putNULL(string key) {
            Data data;
            data.NUL = 0;
            values.insert(make_pair(key, Value(SQLITEWRAPPER_NULL, data)));
        }

        string ContentValues::toString() {
            string sql = "( ";
            map<string, Value>::iterator it;
            for (it = values.begin(); it != values.end(); ++it) {
                string column_name = it->first;
                sql += (column_name + ", ");
            }

            sql += ") ";

            sql += "VALUES (";
            for (it = values.begin(); it != values.end(); ++it) {
                Value value = it->second;
                switch (value.getType()) {
                    case SQLITEWRAPPER_INTEGER:
                        sql += (to_string(value.getData().INT) + ", ");
                        break;
                    case SQLITEWRAPPER_NULL:
                        sql += (string("NULL") + ", ");
                        break;
                    case SQLITEWRAPPER_TEXT:
                        sql += (string("'") + value.getData().TEXT + "', ");
                        break;
                    case SQLITEWRAPPER_FLOAT:
                        sql += (to_string(value.getData().FLOAT) + ", ");
                        break;
                    default:
                        sql += (string("NULL") + ", ");
                        break;
                }
            }

            sql += ");";

            return sql;
        }

        template<class T>
        string ContentValues::to_string( const T& n ) {
            std::ostringstream stm ;
            stm << n ;
            return stm.str() ;
        }
    }
}
